package com.community.contorller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.PageReadListener;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.community.po.PeoplePO;
import com.community.service.RecordService;
import com.lening.common.base.BaseController;
import com.lening.common.web.Result;
import com.community.dto.OwnerDTO;
import com.community.po.OwnerPO;
import com.community.service.OwnerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * @ToDo:
 * @Author：高尚磊
 * @date: 2024/6/4 9:07
 */
@Slf4j
@RestController
@RequestMapping("owner")
public class OwnerController extends BaseController<OwnerPO, OwnerDTO, OwnerService> {
    @Autowired(required = false)
    private OwnerService owner;
    @Autowired(required = false)
    private RecordService recordService;
    @GetMapping("get")
    public List<OwnerPO> get(){
        List<OwnerPO> list = owner.find();
        return list;
    }
//    @GetMapping("getAll")
//    public Result<?> getAllOwner(OwnerDTO ownerDTO){
//        Page<OwnerDTO> page =owner.getAllOwner(ownerDTO);
//        return Result.ok(page);
//    }
//    根据id查询
    @GetMapping("getByTel/{phone}")
    public Result<?> getByTel(@PathVariable("phone") String  phone){
    OwnerPO list = owner.getByTel(phone);
    return Result.ok(list);
    }

    //导出
    @PostMapping("ExportExcel")
    public void ExportExcel() {
        // 设置文件导出的路径
        String realPath = "D:\\office";
        File folder = new File(realPath);
        if (!folder.isDirectory()){
            folder.mkdirs();
        }
        String fileName = realPath  + "OwnerPO" + System.currentTimeMillis() + ".xlsx";
        EasyExcel.write(fileName, OwnerPO.class).sheet("用户表").doWrite(owner.find());
    }
    //导入
    @Transactional(rollbackFor = Exception.class) // 指定任何异常都要回滚事务
    @PostMapping("ImportExcel")
    public void ImportExcel(MultipartFile multipartFile) throws IOException {
        ExecutorService executorService = Executors.newCachedThreadPool();
        if (multipartFile.isEmpty()) {
            return;
        }
        // 这里 需要指定读用哪个class去读，然后读取第一个sheet 文件流会自动关闭
        // 这里每次会读取3000条数据 然后返回过来 直接调用使用数据就行
        EasyExcel.read(multipartFile.getInputStream(), OwnerPO.class, new PageReadListener<OwnerPO>(dataList -> {
            int filedCount=0;
            //获取文件中的总数
            System.out.println(dataList.size());
            try{
                if(1000<dataList.size()){
                    for(int i = 0; i < 1000000 /1000;i++){
                        Future<Boolean> result = executorService.submit(() -> {
                            return owner.saveBatch(dataList);
                        });
                    }
                }else {
                    for (OwnerPO ownerPO : dataList) {
                        try {
                            if (ownerPO.getOwnerName() == null){
                                throw  new IllegalArgumentException("Invalid value for someField: ");
                            }
                            //将导入的数据用mybatisPlus一个个添加进数据库
                            owner.insert(ownerPO);
                        }catch (Exception e){
                            filedCount++;
                            log.error("导入失败,失败数为"+filedCount);
                        }
                    }
                    recordService.adda((long) dataList.size(),(long) dataList.size()-filedCount,(long) filedCount);
                }
            }catch (Exception e){
                log.error("导入失败,失败数为"+filedCount);
            }
        })).sheet().doRead();
    }

}
